package factorytest.iflytek.com.einkiflytekfactorytest.factorytestui;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import factorytest.iflytek.com.einkiflytekfactorytest.FTFloatWindowService;
import factorytest.iflytek.com.einkiflytekfactorytest.R;
import factorytest.iflytek.com.einkiflytekfactorytest.ViewDialogFragment;
import factorytest.iflytek.com.einkiflytekfactorytest.common.ForeLightCtrl;
import factorytest.iflytek.com.einkiflytekfactorytest.common.LedCtrl;
import factorytest.iflytek.com.einkiflytekfactorytest.device.DeviceAttr;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.DebugLog;

public class FactoryFirstActivity extends FactoryBaseActivity {

    private MediaPlayer mediaPlayer;

    private final static int MAX_COUNT = 6;
    private LinearLayout linearLayoutContainer;
    private int[] colorResIds;
    private int currentColorPos;

    private boolean setLongClick = false;

    private final static int MSG_LED_CTRL = 100;
    private final static int PERIOD_LED_CTRL = 1000;//1s

    private int ledOnCount = 0;

    private final int HEADSET_PLUG = 0x01;
    private final int HEADSET_UNPLUG = 0x02;
    private int headsetEvent = (HEADSET_PLUG | HEADSET_UNPLUG);

    private ServiceConnection serviceConnection = new MyServiceConnection();
    private FTFloatWindowService mBindService;

    private class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {

            FTFloatWindowService.MyBinder mBinder = (FTFloatWindowService.MyBinder) binder;
            mBindService = mBinder.getService();

            if (mBindService != null) {
                mBindService.setFloatLayoutVisibility(View.INVISIBLE);
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBindService = null;
        }

    }

    @Override
    int getLayoutId() {
        return R.layout.activity_factory_first;
    }

    @Override
    void onInitView(@Nullable Bundle savedInstanceState) {

        Intent intent = new Intent(this, FTFloatWindowService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

        linearLayoutContainer = (LinearLayout) findViewById(R.id.linearLayoutContainer);
        colorResIds = getResources().getIntArray(R.array.color_gray_level);

        currentColorPos = 0;

        linearLayoutContainer.removeAllViews();
        linearLayoutContainer.setBackgroundColor(Color.WHITE);

        linearLayoutContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentColorPos ++;
                if (currentColorPos >= MAX_COUNT) {
                    currentColorPos = 0;

                    showDialog();
                    Toast.makeText(mContext, R.string.screen_test_toast_can_long_click, Toast.LENGTH_SHORT).show();

                    if (!setLongClick) {
                        setLongClick = true;
                        linearLayoutContainer.setOnLongClickListener(longClickListener);
                    }

                }

                if (currentColorPos == 0) {

                    linearLayoutContainer.removeAllViews();
                    linearLayoutContainer.setBackgroundColor(Color.WHITE);

                } else if (currentColorPos == 1) {

                    linearLayoutContainer.removeAllViews();
                    linearLayoutContainer.setBackgroundColor(Color.BLACK);

                } else {

                    final int pos = currentColorPos - 2;
                    setChildView((pos & 0x1) != 0, (pos & 0x2) != 0);

                }

                if (DeviceAttr.getRunningDeviceAttr().hasForeLight()) {

                    int coldOnFlag = ForeLightCtrl.getForeLightCtrl().getColdLightBrightness() > 0 ? 0x1 : 0;
                    int warmOnFlag = ForeLightCtrl.getForeLightCtrl().getWarmLightBrightness() > 0 ? 0x2 : 0;
                    int onFlag = coldOnFlag | warmOnFlag ;
                    onFlag++;
                    if (onFlag > 0x3) {
                        onFlag = 0;
                    }

                    ForeLightCtrl.getForeLightCtrl().setColdLightBrightness(mContext, ((onFlag & 0x1) != 0) ? ForeLightCtrl.MAX_BRIGHTNESS : 0);
                    ForeLightCtrl.getForeLightCtrl().setWarmLightBrightness(mContext, ((onFlag & 0x2) != 0) ? ForeLightCtrl.MAX_BRIGHTNESS : 0);


                }
            }
        });
    }

    @Override
    void onHandleMessage(Handler handler, Message msg) {

        switch (msg.what) {
            case MSG_LED_CTRL:
                if (++ledOnCount > 10000) {
                    ledOnCount = 0;
                }
                LedCtrl.setLed((0 == (ledOnCount % 2)), LedCtrl.LedAttr.led_green);
                LedCtrl.setLed(!(0 == (ledOnCount % 2)), LedCtrl.LedAttr.led_red);

                handler.sendEmptyMessageDelayed(msg.what, PERIOD_LED_CTRL);

                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();

        Toast.makeText(mContext, R.string.screen_test_toast, Toast.LENGTH_SHORT).show();

        showDialogForHeadsetTest();

        //发送广播检测耳机插入状态
        IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        registerReceiver(headsetPlugReceiver, filter);


        startTestPlaySound();

        startLedCtrl();

        if (mBindService != null) {
            mBindService.setFloatLayoutVisibility(View.INVISIBLE);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        //注销广播接收器
        unregisterReceiver(headsetPlugReceiver);
        stopTestPlaySound();
        stopLedCtrl();

        if (mBindService != null) {
            mBindService.setFloatLayoutVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unbindService(serviceConnection);
    }

    private void startLedCtrl() {
        getHandler().sendEmptyMessage(MSG_LED_CTRL);
    }
    private void stopLedCtrl() {
        getHandler().removeMessages(MSG_LED_CTRL);
        LedCtrl.setLed(false, LedCtrl.LedAttr.led_green, LedCtrl.LedAttr.led_red);
    }

    private void stopTestPlaySound() {

        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();//回收资源
            mediaPlayer = null;
        }
    }

    private void startTestPlaySound() {
        if (mediaPlayer != null) {
            stopTestPlaySound();
        }
        try {
            mediaPlayer = MediaPlayer.create(getContext(), R.raw.music_test_channel);;
            mediaPlayer.setLooping(true);//这种这个后, setOnCompletionListener不能被调用了.
            mediaPlayer.start();
            DebugLog.e("mediaPlayer start ");

        } catch (Exception e) {
            DebugLog.e("exception e = " + e.getMessage());
        }

        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                DebugLog.e("onError, what = " + what + ", extra = " + extra);
                startTestPlaySound();
                return true;
            }
        });

    }

    private void setChildView(boolean colorRevert, boolean vertical) {

        linearLayoutContainer.removeAllViews();

        linearLayoutContainer.setOrientation(vertical ? LinearLayout.VERTICAL : LinearLayout.HORIZONTAL);

        for (int i = 0; i < colorResIds.length; i++) {
            View view = new View(mContext);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            lp.weight = 1;
            int color = colorResIds[i];
            if (colorRevert) {
                color = colorResIds[colorResIds.length - 1 - i];
            }
            view.setBackgroundColor(color);
            view.setClickable(false);
            linearLayoutContainer.addView(view, lp);
        }
    }

    private void showDialog() {

        showFinishDialog(R.string.ft_screen_test_dialog_title, R.string.item_exit_test);

    }

    private View.OnLongClickListener longClickListener =
            new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    showDialog();
                    return true;
                }
            };


    ViewDialogFragment dialogWhenHeadsetUnplug;
    private void dismissDialogForHeadsetTest() {

        if (dialogWhenHeadsetUnplug != null) {
            dialogWhenHeadsetUnplug.dismiss();
            dialogWhenHeadsetUnplug = null;
        }
    }

    private void showDialogForHeadsetTest() {

        if (dialogWhenHeadsetUnplug == null) {
            final String title = getString(R.string.headset_event);
            final String msg = getString(R.string.headset_event_plug_unplug);
            dialogWhenHeadsetUnplug = ViewDialogFragment.newInstance(title, msg, false);
        }

        if (!dialogWhenHeadsetUnplug.isShowing()) {
            dialogWhenHeadsetUnplug.show(getFragmentManager());
        }

    }

    private BroadcastReceiver headsetPlugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (action != null && action.equals(Intent.ACTION_HEADSET_PLUG)) {
                if (intent.hasExtra("state")) {

                    boolean unplug = (intent.getIntExtra("state", 0) == 0);
                    DebugLog.e("unplug = " + unplug);


                    if (unplug) {

                        headsetEvent &= ~HEADSET_UNPLUG;

                    } else {

                        headsetEvent &= ~HEADSET_PLUG;
                    }

                    if (headsetEvent == 0 ) {
                        dismissDialogForHeadsetTest();
                    }
                }
            }
        }
    };
}
